package wang.lx.mybatis.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import wang.lx.mybatis.common.SysDefaultRole;
import wang.lx.mybatis.entity.SysRole;
import wang.lx.mybatis.entity.SysUser;
import wang.lx.mybatis.service.SysUserServiceI;

public class MyRealm  extends AuthorizingRealm{

    @Autowired
    SysUserServiceI sysUserServiceI;
    
    public boolean supports(AuthenticationToken token) {
        return token != null && UsernamePasswordToken.class.isAssignableFrom(token.getClass());
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        SysUser sysuser = (SysUser)arg0.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        for(SysRole role : sysuser.getRoles()){
            roles.add(role.getRolename());
        }
        info.setRoles(roles);
        return info;
    }

    /**
     * 认证，正常用于登录使用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account = (String)token.getPrincipal();
        String pwd = new String((char[])token.getCredentials());
        SysUser query = new SysUser();
        //query.setAccount(account);
        query.setAccount(account);
        SysUser sysuser = this.sysUserServiceI.findUserByUser(query);
        boolean isok = true;
        if(sysuser == null){
            isok = false;
        }
        else 
        {
            // 判断密码
            isok = sysuser.getPwd().equals(pwd);
        }
        if(!isok)
            throw new AuthenticationException("用户名或密码错误");
        //TODO 获取角色与权限信息
        {
            SysRole role = new SysRole();
            role.setId(SysDefaultRole.ROLE_USER.getRoleId());
            role.setRolename(SysDefaultRole.ROLE_USER.getRoleName());
            sysuser.getRoles().add(role);
            role = new SysRole();
            role.setId(SysDefaultRole.ROLE_ADMIN.getRoleId());
            role.setRolename(SysDefaultRole.ROLE_ADMIN.getRoleName());
            sysuser.getRoles().add(role);
            // 设置当前角色
            sysuser.setCurrentRole(role);
        }

        AuthenticationInfo info = new SimpleAuthenticationInfo(sysuser, sysuser.getPwd(), getName());
        return info;
    }
    
}
